import React, { useEffect, useState } from "react";
import { useRef } from "react";
import style from "./style.module.css"
import BulletScreen, { StyledBullet } from 'rc-bullets';

const UseCamera = (props) => {
  // 弹幕屏幕

  const [screen, setScreen] = useState(null);
  // 弹幕内容
  const [bullet, setBullet] = useState('');
  useEffect(() => {
    // 给页面中某个元素初始化弹幕屏幕，一般为一个大区块
    let s = new BulletScreen('.screen');
    // or
    // let s=new BulletScreen(document.querySelector('.screen));
    setScreen(s);
  }, []);
  // 弹幕内容输入事件处理
  const handleChange = ({ target: { value } }) => {
    setBullet(value);
  };
  // 发送弹幕
  const handleSend = () => {
    if (bullet) {
      // push
      screen.push(bullet);
      // or 使用 StyledBullet
      screen.push(
        <StyledBullet
          head="https://zerosoul.github.io/rc-bullets/assets/img/heads/girl.jpg"
          msg={bullet}
        />
      );
    }
  };
  let video_ref = useRef();

  const hanlefhCamera = () => {
    props.history.push('/layout/liveManage')
  }

  async function getMedia() {
    let video = video_ref.current;
    let constraints = {
      video: { width: 500, height: 500 },
      audio: true,
    };

    try {
      let MediaStream = await navigator.mediaDevices.getUserMedia(constraints);
      video.srcObject = MediaStream;
      video.play();
    } catch (e) {
      alert(e);
    }
  }
  //关闭摄像头
  const getMedias=()=>{
    let video = video_ref.current;
        console.log(video);
        // video.srcObject.stop()
        video.srcObject.getTracks()[1].stop()
        console.log(video.srcObject.getTracks());
  }
  useEffect(() => {
    
  }, []);
  return (
    <div className={style.cameraBox}>
      <div style={{ display: "flex", flexDirection: "column" }}>
        <video
          ref={video_ref}
          height="800px"
          autoPlay={true}
          width="700px"
        ></video>
        <br />
        <div className={style.btnBox}>
          <button className={style.btnlive} onClick={() => { getMedia() }}>开始直播</button>
          <button className={style.btnlive} onClick={() => { getMedias() }}>关闭摄像头</button>
          <button className={style.liveFhBox} onClick={() => hanlefhCamera()}>返回</button>
        </div>
      </div>
      <div className={style.screens}>
        <div className="screen" style={{ width: '450px', height: '700px' }}></div>
        <input value={bullet} onChange={handleChange} />
        <button onClick={handleSend}>发送</button>
      </div>
    </div>
  );
};

export default UseCamera